import { WebApp } from "meteor/webapp";
import { createResource, createSimpleRoute } from "./route-base";

// 中间件链式调用执行器
function useMiddleware(middlewares, handler) {
  return async (req, res, next) => {
    let index = 0;
    
    // 支持异步中间件的递归执行函数
    const run = async (err) => {
      if (err) return next(err);
      if (index >= middlewares.length) return handler(req, res, next);
      
      const middleware = middlewares[index++];
      // 处理异步中间件（支持async/await）
      try {
        await middleware(req, res, run);
      } catch (error) {
        next(error);
      }
    };
    
    await run();
  };
}

/**
 * 路由组创建函数
 * @param {Object} options - 路由组配置
 * @param {string} options.prefix - 路由前缀
 * @param {Array} options.middlewares - 中间件数组
 * @param {Function} defineRoutes - 路由定义函数，接收路由工具对象
 */
export function group({ prefix = "", middlewares = [] }, defineRoutes) {
  // 局部路由添加函数（带前缀和中间件）
  const addRoute = (method, path, handler) => {
    const fullPath = `${prefix}${path}`;
    const wrappedHandler = useMiddleware(middlewares, handler);
    
    WebApp.connectHandlers.use(fullPath, (req, res, next) => {
      if (req.method === method.toUpperCase()) {
        wrappedHandler(req, res, next);
      } else {
        next(); // 方法不匹配时交给下一个处理器
      }
    });
  };

  // 生成路由组内的资源路由和简单路由工具
  const resource = createResource(addRoute);
  const simpleRoute = createSimpleRoute(addRoute);

  // 执行路由定义，传入局部路由工具
  defineRoutes({ addRoute, resource, simpleRoute });
}